# -*- coding: utf-8 -*-
# @Time    : 2018/4/2 10:14
# @Author  : shiweixian

import re
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed


def pdf_2_text(path):
    """
    将pdf转为文本
    :param path:
    :return:
    """
    # 段落
    sections = []
    file = open(path, 'rb')  # 以二进制读模式打开
    # 用文件对象来创建一个pdf文档分析器
    praser = PDFParser(file)
    # 创建一个PDF文档
    doc = PDFDocument()
    # 连接分析器 与文档对象
    praser.set_document(doc)
    doc.set_parser(praser)

    # 提供初始化密码
    # 如果没有密码 就创建一个空的字符串
    doc.initialize()

    # 检测文档是否提供txt转换，不提供就忽略
    if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed

    # 创建PDf 资源管理器 来管理共享资源
    rsrcmgr = PDFResourceManager()
    # 创建一个PDF设备对象
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    # 创建一个PDF解释器对象
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    # 循环遍历列表，每次处理一个page的内容
    for page in doc.get_pages():  # doc.get_pages() 获取page列表
        interpreter.process_page(page)
        # 接受该页面的LTPage对象
        layout = device.get_result()
        for x in layout:
            if hasattr(x, "get_text"):
                sections.append(x.get_text)
    return sections


def analyse_section(csv_filename, abstract, item, document_url='', title=''):
    """
    分析摘要，如果该摘要含有最佳PH等，则保存
    :param abstract:
    :param item:
    :param document_url: 论文文档所在网页的网址
    :return:
    """
    print('开始分析摘要')
    # 如果摘要中含有这个蛋白质的名称
    index = 0
    # if abstract.__contains__(protein_name):
    sentences = abstract.split('.')
    print('包含该蛋白质')
    index += 1
    if index % 10 == 0:
        print('第 ' + str(index) + ' 条')
    # 是否包含最佳PH、温度
    list = []
    for sentence in sentences:
        if sentence.__contains__(' optimum ') or sentence.__contains__(' optimal ') or sentence.__contains__(
                ' activity '):
            words = sentence.split(' ')
            print(sentence)
            dict = {'sentence': sentence}
            for i in range(len(words)):
                if 'ph' == words[i].lower() and words[i + 1] is not None and re.match(
                        '\d+(\.\d+)?(-)?(\d+\.)?(\d+)?', words[i + 1]):
                    pH = words[i + 1]
                    print('PH=' + pH)
                    dict['PH'] = pH
                if words[i] == 'degree' and re.match(
                        '\d+(\.\d+)?(-)?(\d+\.)?(\d+)?', words[i - 1]):
                    print('温度=' + words[i - 1])
                    dict['T'] = words[i - 1]
                elif words[i].__contains__('°C'):
                    T = words[i].replace('°C', '').replace(',', '').replace('.', '').strip()
                    print('温度=' + T)
                    dict['T'] = T
            if 'PH' in dict.keys() or 'T' in dict.keys():
                list.append(dict)

    if list.__len__() > 0:
        file = open(csv_filename, 'a', encoding='utf-8')
        writer = csv.writer(file)
        for dict in list:
            row = [item['org_name'], item['protein_name'], item['name'],
                   dict['PH'] if 'PH' in dict.keys() else '',
                   dict['T'] if 'T' in dict.keys() else '', dict['sentence'], abstract, document_url, title]
            writer.writerow(row)
        file.close()


if __name__ == '__main__':
    path = u'document12.pdf'
    sections = pdf_2_text(path)
    print(sections.__len__())
    for section in sections:
        text_analyze(section)
